//
//  GamePlayer.m
//  Galaxy
//
//  Created by antl on 1/28/13.
//  Copyright (c) 2013 __MyCompanyName__. All rights reserved.
//

#import "GamePlayer.h"
#import "SimpleAudioEngine.h"
#import "MenuScene.h"
static CGPoint VITRI_ENEMY[]={
    {40,400},{90,400},{140,400},{190,400},{240,400},{290,400},           
    {40,300},{90,300},{140,300},{190,300},{240,300},{290,300},  
    
};
@implementation GamePlayer
-(id) init
{
	if(self==[super init])
	{
        typeBullet=NOMARL_BULLET;
        enableShooting=TRUE;
        self.isTouchEnabled = YES;
        [self initBackground];
       
        [self schedule:@selector(update:) interval:kEnemyMoveSpeed];     
        [self initBackground];
        [self setupInit];
        
        [self addEnemy];
        [self schedule:@selector(actionUpdate:) interval:1/60];
        
         CCMenuItemFont* btBack=[CCMenuItemFont itemWithString:@"Back"  target:self selector:@selector(back)];
         btBack.position=ccp(-120,220);
         CCMenu * iMenu=[CCMenu menuWithItems:btBack,nil];
        [self addChild:iMenu];
    }
    return self;
}
-(void)back
{
    [self changePageWithScene:[MenuScene node] type:FlipX];
}
-(void)dealloc
{
    [super dealloc];
    SAFE_RELEASE(listEnemy);
    SAFE_RELEASE(listBullet);
}
-(void)setupInit{   
    listEnemy=[[NSMutableArray alloc] init];
    listBullet = [[NSMutableArray alloc] init];
}
#pragma mark - INIT-
-(void)initBackground
{    /// ADD BACKGROUND GAME
   // [self DrawImageSpritebyLayer:self andFileName:@"bg.png" atPosition:ccp(0,0) withZ:0 andScale:0 AnchorPoint:ccp(0,0)];

}

-(void)initNewEnemy
{
    
    for (int index=0; index<NumberEnemy; index++) {
        
        NSLog(@"init new enemy");
        int vitriXuatHien=rand()%12;//VITRI_ENEMY count
        Enemy *en=[[Enemy alloc] initWithType:eType1 andPosition:VITRI_ENEMY[vitriXuatHien] andSelf:self] ;
        if(vitriXuatHien%2==0)
        {
            en.moveLeft=TRUE;
        }
       
        [listEnemy addObject:en];		
        SAFE_RELEASE(en);
    }
}
#pragma mark - UPDATE - TIMER
- (void)update:(ccTime)dt {
    
    for ( Enemy* eN  in listEnemy)
    {        
        if(eN!=nil)
        {                
            [eN enemyMove];
           
        }
        
    }
}
- (void)actionUpdate:(ccTime)dt {
    
    NSMutableArray *ListBullet = [[NSMutableArray alloc] init];
    for (CCSprite *bullet in listBullet) {
        CGRect bulletRect = CGRectMake(bullet.position.x - (bullet.contentSize.width/2), 
										   bullet.position.y - (bullet.contentSize.height/2), 
										   bullet.contentSize.width, 
										   bullet.contentSize.height);
        NSMutableArray *enemyDelete = [[NSMutableArray alloc] init];
         BOOL isShoot=FALSE;
        for (Enemy *iEnemy in listEnemy) {
            /// NSLog(@"++++++%d",iEnemy.health);
            CGRect iEnemyRect = CGRectMake(iEnemy.enemy.position.x - (iEnemy.enemy.contentSize.width/4), 
										   iEnemy.enemy.position.y - (iEnemy.enemy.contentSize.height/4), 
										   iEnemy.enemy.contentSize.width/2, 
										   iEnemy.enemy.contentSize.height/2);
           
			if (CGRectIntersectsRect(bulletRect, iEnemyRect)) {
               // NSLog(@"iEnemyRect %8.3f -%8.3f %8.3f %8.3f",iEnemyRect.origin.x,iEnemyRect.origin.y,iEnemyRect.size.width,iEnemyRect.size.height);
                iEnemy.health--;
                isShoot=TRUE;
                //NSLog(@"------------%d",iEnemy.health);
                if(iEnemy.health<=0)
                {
                   // NSLog(@"%d",iEnemy.health);
                    [enemyDelete addObject:iEnemy];	
                }
			}
        }
        /////////////////////////
        for (Enemy *target in enemyDelete) {
           // [[SimpleAudioEngine sharedEngine] playEffect:@"Bomb_Exploding-Sound_Explorer-68256487.mp3"];
            AnimationClass *explosion=[self addImageAnimationByClass:[EXPLOSION class] withZ:10];
            explosion.position=target.enemy.position;
            id Action1 = [explosion createAnimationOneTime];
            [explosion runAction:[CCSequence actions:
                               Action1,
                               [CCCallFuncN actionWithTarget:self selector:@selector(removeExposion:)],
                               nil]];
            
            
			[listEnemy removeObject:target];
			[target.enemy removeFromParentAndCleanup:TRUE];
			//_projectilesDestroyed++;
			//if (_projectilesDestroyed >= NumberEnemy) {
				/////// Win Game
			//}
            
            [self addEnemy];
           
            
		}
		
		if (enemyDelete.count > 0||isShoot==TRUE)
        {
			[ListBullet addObject:bullet];
		}
		[enemyDelete release];
        
    }
    
    for (CCSprite *projectile in ListBullet) {
		[listBullet removeObject:projectile];
		[self removeChild:projectile cleanup:YES];
	}
	[ListBullet release];
}
-(void)addEnemy
{
    id delayOneTime=[CCDelayTime actionWithDuration:0.5];
    id ActionAddNewEnemy=[CCCallFunc actionWithTarget:self selector:@selector(addNewEnemy)];
    
    [self runAction:[CCSequence actions:delayOneTime,ActionAddNewEnemy,nil]];
}
#pragma Mark -  SHOOTING START--------
CGPoint TOUCH_BEGIN;
CGPoint TOUCH_BGINTEMP;
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [self convertTouchToNodeSpace:touch];
    TOUCH_BEGIN=ccp(location.x,10);
    TOUCH_BGINTEMP=location;

}

-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
     ///enableShooting=TRUE;
    
    
    UITouch *touch = [touches anyObject];
    CGPoint location = [self convertTouchToNodeSpace:touch];
    
    
    
    if (location.y<TOUCH_BGINTEMP.y) {
        return;
    }
    
    
    // Set up initial location of projectile
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    CCSprite *bullet=[CCSprite spriteWithFile:[self getBulletByType:typeBullet]];
    bullet.position=TOUCH_BEGIN;
   [self addChild:bullet];
    
    // Determine offset of location to projectile
    CGPoint offset = ccpSub(location,bullet.position);
    ///NSLog(@"offset  %8.3f-%8.3f",offset.x,offset.y);
    int realY = winSize.height + (bullet.contentSize.height/2);
     //NSLog(@"------------------------------------");
   
    
    float ratio = (float) offset.x / (float) offset.y;
    int realX = (realY * ratio) + bullet.position.x; 
    
    //NSLog(@"realX %d   realY %d  ratio=%8.3f",realX,realY,ratio);
   
    CGPoint realDest = ccp(realX, realY);
    
    
    
        
    
    // Determine the length of how far you're shooting
    int offRealX = realX - bullet.position.x;
    int offRealY = realY - bullet.position.y;
    
    float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY));
    
    
    
    
    
     
    float realMoveDuration = length/kVelocityBullet; ///   S/480pixels/2sec
    
    [bullet runAction:[CCSequence actions:                              
    						   [CCMoveTo actionWithDuration:realMoveDuration position:realDest],
    						   [CCCallFuncN actionWithTarget:self selector:@selector(bulletMoveFinished:)],
    						   nil]];
    
    id action2 = [CCRotateBy actionWithDuration:0.1 angle:360];
    id repeat =  [CCRepeatForever actionWithAction:action2];
    [bullet  runAction:repeat];
     [listBullet addObject:bullet];
    
}

// Move projectile to actual endpoint
//    [bullet runAction:
//     [CCSequence actions:
//      [CCMoveTo actionWithDuration:realMoveDuration position:realDest],
//      [CCCallBlockN actionWithBlock:^(CCNode *node) {
//         [node removeFromParentAndCleanup:YES];
//     }],
//      nil]];



-(void)addNewEnemy
{
    [self initNewEnemy];
}
-(void)removeExposion:(id)sender
{
    AnimationClass *explosion=(AnimationClass *)sender;
    [explosion removeFromParentAndCleanup:TRUE];
}
-(void)bulletMoveFinished:(id)sender {
    
    CCSprite *sprite = (CCSprite *)sender;
	[self removeChild:sprite cleanup:YES];
    [listBullet removeObject:sprite];
}
-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
    enableShooting=FALSE;
}
#pragma Mark -  SHOOTING END--------
-(NSString*)getBulletByType:(BULLET_TYPE)type
{
    switch (type) {
        case NOMARL_BULLET:
           return  @"shuriken-icon.png";
            break;
        case STRONG_BULLET:
            return  @"";
            break;
        case ULTIL:
            return  @"";
            break;
        default:
            return  @"";
            break;
    }
}
@end
